package com.cjh.mybatis10.executor;

import com.cjh.mybatis10.executor.statement.StatementHandler;
import com.cjh.mybatis10.mapping.BoundSql;
import com.cjh.mybatis10.mapping.MappedStatement;
import com.cjh.mybatis10.session.Configuration;
import com.cjh.mybatis10.session.ResultHandler;
import com.cjh.mybatis10.session.RowBounds;
import com.cjh.mybatis10.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @Descripton 简单执行器
 * @Author cjh
 * @Date 2023/6/1 10:27
 */
public class SimpleExecutor extends BaseExecutor {
    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    protected <E> List<E> doQuery(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        try {
            Configuration configuration1 = mappedStatement.getConfiguration();

            // 新建一个 StatementHandler
            StatementHandler handler = configuration.newStatementHandler(this, mappedStatement, parameter, rowBounds, resultHandler, boundSql);

            Connection connection = transaction.getConnection();

            // 准备语句
            Statement stmt = handler.prepare(connection);
            handler.parameterize(stmt);
            // 返回结果
            return handler.query(stmt, resultHandler);

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
